library(tidyverse)
library(sf)
library(gridExtra)
library(Cairo)
library(lubridate)

# Set font for cairo png
CairoFonts(
  regular="Times:style=Regular"
)



# Pull in countries for base map ------------------------------------------

# All countries in Africa + Yemen
afnames <- raster::ccodes() %>% 
  filter(continent == "Africa" | NAME == "Yemen") %>% 
  dplyr::select(NAME)

temp0 <- vector("list", 0)
for(i in afnames$NAME) {
  print(i)
  temp0[[i]] <- raster::getData(name = "GADM", 
                                country = i, 
                                download = T, 
                                level = 0)
}

# Join into sf frame
joined0 <- list(temp0, makeUniqueIDs = T) %>% 
  purrr::flatten() %>% 
  do.call(rbind, .) %>% 
  st_as_sf()


# Load data and bring in geo ----------------------------------------------

load(here::here("Grids", "df_grid_clean.Rdata"))


df_grid_clean <-
  df_grid_clean %>% 
  mutate(date_ml2 = case_when(date_cs < lubridate::ymd("2016-02-01") ~ date_cs %m-% months(3),
                              TRUE ~ date_cs %m-% months(4)))


# Set factor variables for filling cells
df_grid_clean <- df_grid_clean %>% 
  mutate(CS = as.factor(CS),
         ML1 = as.factor(ML1),
         ML2 = as.factor(ML2),
         diff_factor = as.factor(diff))



# Bias maps ---------------------------------------------------------------

# Color pal
mypal <- scales::viridis_pal(option = "magma")(7)
mypal[4] <- "gray90"


# Function to save individual maps
mapper <- function(x, data, var) {
  
  Cairo(width = 8, height = 12, file=here::here("Words", "Figures", "Manuscript",
                                                "Final", "Snippets", "Bias",
                                                paste0("bias_", x, ".png")), 
        type="png", 
        pointsize=12,
        bg = "white", 
        canvas = "white", 
        units = "in", 
        dpi = 400)
  
  
  dat = filter(data, !is.na(UQ(var)) & date_ml2 == x) 
  
  gg <- 
    ggplot() +
    geom_sf(data = joined0,
            color = "white", fill = "gray97", size = 1) +
    geom_sf(data = dat, aes(fill = diff_factor), color = "transparent") +
    
    scale_fill_manual(values = mypal,
                      guide = guide_legend(title = "Bias", nrow = 1), 
                      drop = F) +
    theme_minimal() +
    coord_sf(xlim = c(-20, 60),
             ylim = c(-40, 40)) +
    theme(axis.text = element_blank(),
          panel.background = element_rect(color = "gray90", size = 2),
          panel.grid = element_line(linetype = 3),
          legend.position = "bottom",
          text = element_text(family = "serif"),
          title = element_text(size = 14),
          axis.title = element_text(size = 12),
          strip.text = element_text(size = 11),
          legend.text = element_text(size = 12)) +
    labs(title = x)
  
  
  temp_nog <- dat
  temp_nog$geometry <- NULL
  tab <-
    temp_nog %>% filter(!is.na(ML2)) %>% 
    group_by(ML2) %>% 
    mutate(col_tot = n()) %>% 
    group_by(ML2, diff) %>% 
    summarise(pred_tot = n(), col_tot = first(col_tot)) %>% 
    ggplot() +
    geom_tile(aes(x = as.numeric(ML2), y = as.numeric(diff), fill = pred_tot/ col_tot)) +
    geom_text(aes(x = as.numeric(ML2), y = as.numeric(diff), label = paste0(100 * round(pred_tot/ col_tot, 3), "%")),
              color = "white", check_overlap = T, fontface = "bold") +
    theme_minimal() +
    labs(x = "Level of Food Security for FEWS NET Medium-Term Projection", y = "Bias") +
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_line(size = 1, color = "gray90"),
          panel.ontop = T,
          text = element_text(family = "serif"),
          title = element_text(size = 14),
          axis.text = element_text(size = 12),
          axis.title = element_text(size = 12),
          strip.text = element_text(size = 11),
          legend.text = element_text(size = 12)) +
    scale_fill_gradient(low = "gray60",high = "gray10",
                        guide = F) +
    scale_x_continuous(limits = c(0.5,4.5), 
                       breaks = seq(1,4,1),
                       labels = seq(1,4,1)) +
    scale_y_continuous(limits = c(-3,3), 
                       breaks = seq(-3,3,1),
                       labels = seq(-3,3,1))

  grid.arrange(arrangeGrob(gg, tab, ncol = 1, heights = c(3, 1)))
  
  

  
  dev.off()
  
  
  
  
} 

# Iterate through each date
unique(df_grid_clean$date_ml2[!is.na(df_grid_clean$diff)]) %>% 
  map(~mapper(x = ., var = "diff_factor", data = df_grid_clean[!is.na(df_grid_clean$diff),]))





# ML1, ML2 and CS maps ----------------------------------------------------


mapper_notab <- function(x, var, legtitle, data) {

  Cairo(width = 8, height = 8, file=here::here("Words", "Figures", "Manuscript",
                                                "Final", "Snippets",
                                                paste0(var, "_", x, ".png")),
        type="png",
        pointsize=12,
        bg = "white",
        canvas = "white",
        units = "in",
        dpi = 400)

  # print(x)
  if(var %in% c("ML2", "ML1")){
    dat = filter(data, !is.na(UQ(var)) & date_ml2 == x)
    } else(dat = filter(data, !is.na(UQ(var)) & date_cs == x))

  gg <- 
    ggplot() +
    geom_sf(data = joined0,
            color = "white", fill = "gray97", size = 1) +
    geom_sf(data = dat, aes_string(fill = var), color = "transparent") +
    
    scale_fill_manual(values = scales::viridis_pal(option = "inferno", 
                                                   begin = 0.1)(7),
                      guide = guide_legend(title = NULL, nrow = 1), 
                      drop = F) +
    theme_minimal() +
    coord_sf(xlim = c(-20, 60),
             ylim = c(-40, 40)) +
    theme(axis.text = element_blank(),
          panel.background = element_rect(color = "gray90", size = 2),
          panel.grid = element_line(linetype = 3),
          legend.position = "bottom",
          text = element_text(family = "serif"),
          title = element_text(size = 14),
          axis.title = element_text(size = 12),
          strip.text = element_text(size = 11),
          legend.text = element_text(size = 12)) +
    labs(title = x,
         x = legtitle)
  
  print(gg)
  
  
  
  
  dev.off()
  
  
  
  
} 




# CS maps
unique(df_grid_clean$date_cs[!is.na(df_grid_clean$CS)]) %>% 
  map(~mapper_notab(x = ., 
                    data = df_grid_clean[!is.na(df_grid_clean$CS),],
                    var = "CS", 
                    legtitle = "Level of Food Security for FEWS NET Current Status Assessment"))




# # ML2 maps
# df_grid_clean <- 
#   df_grid_clean %>% 
#   mutate(date_ml2 = case_when(date_cs < lubridate::ymd("2016-02-01") ~ date_cs %m-% months(3),
#                               TRUE ~ date_cs %m-% months(4)))

unique(df_grid_clean$date_ml2[!is.na(df_grid_clean$ML2)]) %>% map(~mapper_notab(x = ., 
                                             var = "ML2", 
                                             data = df_grid_clean[!is.na(df_grid_clean$ML2),],
                                             legtitle = "Level of Food Security for FEWS NET Medium-Term Projection"))



# ML1 maps
unique(df_grid_clean$date_ml2) %>% 
  map(~mapper_notab(x = ., 
                    var = "ML1", 
                    data = df_grid_clean,
                    legtitle = "Level of Food Security for FEWS NET Near-Term Projection"))


table( df_grid_clean$date_cs, df_grid_clean$CS)
table( df_grid_clean$date_cs, df_grid_clean$ML1)
table( df_grid_clean$date_ml2, df_grid_clean$ML2)


